package com.ctshk.sapp.order.tour.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ctshk.common.annotations.OperationLogAnnotation;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.OperationLogModel;
import com.ctshk.common.enums.OperationLogType;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.web.support.BaseController;
import com.ctshk.rpc.order.tour.dto.*;
import com.ctshk.rpc.order.tour.dto.custom.CustomOrderTouristInfoListCollectionDTO;
import com.ctshk.rpc.order.tour.dto.custom.CustomOrderTouristInfoPreviewInvoiceDTO;
import com.ctshk.rpc.order.tour.req.*;
import com.ctshk.rpc.order.tour.req.custom.CustomOrderIdReq;
import com.ctshk.rpc.order.tour.service.ISeriesOrderTouristInfoService;
import com.ctshk.rpc.order.tour.vo.ExcelData;
import com.ctshk.rpc.order.tour.vo.ExcelTemp;
import com.ctshk.rpc.order.tour.vo.ExportExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 系列团游客信息 前端控制器
 * </p>
 *
 * @author 谭响
 * @since 2021-01-18
 */
@Api(value="游客信息", tags="游客信息")
@RestController
@RequestMapping("/series/order/tourist/info")
public class SeriesOrderTouristInfoController extends BaseController {

    @DubboReference
    private ISeriesOrderTouristInfoService iSeriesOrderTouristInfoService;


    @ApiOperation(value = "编辑", notes = "编辑（旅客信息-编辑资料）")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.UPDATE, operTitle = "旅客信息-编辑资料", operDesc = "旅客信息-编辑资料")
    @PostMapping("/edit")
    public Result<SeriesOrderDTO> edit(@RequestBody @Valid SeriesOrderTouristInfoEditReq seriesOrderTouristInfoEditReq) {
        seriesOrderTouristInfoEditReq.setUserId(getCurrentUser(getRequest()).getId());
        return iSeriesOrderTouristInfoService.edit(seriesOrderTouristInfoEditReq);
    }

    @ApiOperation(value = "列表", notes = "列表（旅客信息）")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.QUERY, operTitle = "旅客信息", operDesc = "旅客信息")
    @PostMapping("/list")
    public Result<PageResponse<SeriesOrderTouristInfoDTO>> list(@RequestBody SeriesOrderTouristInfoListReq seriesOrderTouristInfoListReq) {
        seriesOrderTouristInfoListReq.setUserId(getCurrentUser(getRequest()).getId());
        return Result.success(iSeriesOrderTouristInfoService.list(seriesOrderTouristInfoListReq));
    }

    @ApiOperation(value = "收款列表", notes = "收款列表（叶冠峰）")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.QUERY, operTitle = "收款管理", operDesc = "收款管理")
    @PostMapping("/list/collection")
    public Result<PageResponse<CustomOrderTouristInfoListCollectionDTO>> listCollection(@RequestBody CustomOrderIdReq req) {
        req.setUserId(getCurrentUser(getRequest()).getId());
        return Result.success(iSeriesOrderTouristInfoService.listCollection(req));
    }

    @ApiOperation(value = "列表收款团期", notes = "列表（旅行團詳情-收款明細）")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.QUERY, operTitle = "旅行團詳情-收款明細", operDesc = "旅行團詳情-收款明細")
    @PostMapping("/list/collection/trip")
    public Result<PageResponse<SeriesOrderTouristInfoListCollectionTripDTO>> listCollectionTrip(@RequestBody SeriesOrderTouristInfoListCollectionTripReq req) {
        req.setUserId(getCurrentUser(getRequest()).getId());
        return Result.success(iSeriesOrderTouristInfoService.listCollectionTrip(req));
    }

    @ApiOperation(value = "添加", notes = "添加（旅客信息-添人）")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.ADD, operTitle = "旅客信息-添人", operDesc = "旅客信息-添人")
    @PostMapping("/add")
    public Result add(@RequestBody @Valid SeriesOrderTouristInfoAddReq req) {
        req.setUserId(getCurrentUser(getRequest()).getId());
        return iSeriesOrderTouristInfoService.add(req);
    }

    /**
     * 获取文件扩展名(后缀)
     * @param filename
     * @return
     */
    public String getFileExtension(String filename) {
        if (StringUtils.isNotBlank(filename)) {
            String string = filename.trim();
            int index = filename.lastIndexOf(".");
            if (index > 0 && index < string.length() - 1) {
                return string.substring(index + 1);
            }
        }
        return null;
    }

    @ApiOperation(value = "删除", notes = "删除（旅客信息-删除）")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.DELETE, operTitle = "旅客信息-删除", operDesc = "旅客信息-删除")
    @PostMapping("/delete")
    public Result delete(@RequestBody @Valid SeriesOrderTouristInfoDeleteReq req) {
        req.setUserId(getCurrentUser(getRequest()).getId());
        return iSeriesOrderTouristInfoService.delete(req);
    }

    @ApiOperation(value = "旅客名单列表" , notes = "旅客名单列表(张志朋)")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.QUERY, operTitle = "旅客名单列表", operDesc = "旅客名单列表")
    @PostMapping("/nameList")
    public Result<PageResponse<SeriesOrderTouristNameListDTO>> list(@RequestBody SeriesOrderTouristNameListReq touristNameListReq){
        return Result.success(iSeriesOrderTouristInfoService.nameList(touristNameListReq));
    }

    @ApiOperation(value = "旅客分组列表" , notes = "旅客分组列表")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.QUERY, operTitle = "旅客分房分组列表", operDesc = "旅客分房分组列表")
    @PostMapping("/groupList")
    public Result<PageResponse<SeriesOrderTouristRoomGroupDTO>> groupList(@RequestBody @Valid SeriesOrderTouristRoomReq roomReq){
        return Result.success(iSeriesOrderTouristInfoService.queryList(roomReq));
    }

    @ApiOperation(value = "旅客分房查询" , notes = "旅客分房查询")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.QUERY, operTitle = "旅客分房查询", operDesc = "旅客分房查询")
    @PostMapping("/roomList")
    public Result<List<SeriesOrderTouristRoomDTO>> query(@RequestBody @Valid SeriesOrderTouristRoomReq roomReq){
        List<SeriesOrderTouristRoomDTO> result = iSeriesOrderTouristInfoService.roomList(roomReq);
        return Result.success(result);
    }

    @ApiOperation(value = "noShow", notes = "noShow")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.UPDATE, operTitle = "noShow", operDesc = "noShow")
    @PostMapping("/noShow")
    public Result noShow(@RequestBody @Valid SeriesOrderTouristNoShowReq req) {

        return iSeriesOrderTouristInfoService.noShow(req);
    }

    @ApiOperation(value = "状态", notes = "状态")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.UPDATE, operTitle = "状态", operDesc = "状态")
    @PostMapping("/lockStatus")
    public Result lockStatus(@RequestBody @Valid SeriesOrderTouristNoShowReq req){
        return iSeriesOrderTouristInfoService.lockStatus(req);
    }

    @ApiOperation(value = "游客分组", notes = "游客分组")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.UPDATE, operTitle = "游客分组", operDesc = "游客分组")
    @PostMapping("/group")
    public Result group(@RequestBody @Valid SeriesRoomGroupReq roomGroupReq){
        roomGroupReq.setUserId(getCurrentUser(getRequest()).getId());
        return iSeriesOrderTouristInfoService.group(roomGroupReq);
    }

    @ApiOperation(value = "游客分房", notes = "游客分房")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.UPDATE, operTitle = "游客分房", operDesc = "游客分房")
    @PostMapping("/room")
    public Result room(@RequestBody @Valid SeriesRoomRoomReq roomReq){
        return iSeriesOrderTouristInfoService.updateRoom(roomReq,getCurrentUser(getRequest()).getId());
    }


    @ApiOperation(value = "旅客名单旅行团信息", notes = "旅客名单旅行团信息")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.UPDATE, operTitle = "旅行团数据", operDesc = "旅行团数据")
    @GetMapping("/tourist/{id}")
    public Result<SeriesGroupTouristInfoDTO> groupInfo(@PathVariable Long id){
        return Result.success(iSeriesOrderTouristInfoService.groupInfo(id));
    }

    @ApiOperation(value = "详情", notes = "详情（旅客信息-编辑资料-详情）")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.OTHER, operTitle = "旅客信息-编辑资料-详情", operDesc = "旅客信息-编辑资料-详情")
    @PostMapping("/detail")
    public Result<SeriesOrderTouristInfoDetailDTO> detail(@RequestBody @Valid SeriesOrderTouristInfoDetailReq req) {
        req.setUserId(getCurrentUser(getRequest()).getId());
        return iSeriesOrderTouristInfoService.detail(req);
    }


    @ApiOperation(value = "旅客名单获取组信息", notes = "根据团期id查询组信息")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.UPDATE, operTitle = "根据团期id查询组信息", operDesc = "根据团期id查询组信息")
    @GetMapping("/queryGroup/{id}")
    public Result<List<SeriesOrderTouristGroupDTO>> queryGroup(@PathVariable Long id){
       return iSeriesOrderTouristInfoService.queryGroup(id);
    }

    @ApiOperation(value = "新增游客分组", notes = "新增游客分组")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.ADD, operTitle = "新增游客分组", operDesc = "新增游客分组")
    @GetMapping("/addGroup/{scheduleId}")
    public Result addGroup(@PathVariable Long scheduleId){
        return iSeriesOrderTouristInfoService.addGroup(scheduleId,getCurrentUser(getRequest()).getId());
    }

    @ApiOperation(value = "删除游客分组", notes = "删除游客分组")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.DELETE, operTitle = "删除游客分组", operDesc = "删除游客分组")
    @GetMapping("/deleteGroup/{groupId}")
    public Result deleteGroup(@PathVariable("groupId") Long groupId){
        return iSeriesOrderTouristInfoService.deleteGroup(groupId,getCurrentUser(getRequest()).getId());
    }

    @ApiOperation(value = "移除分组下的游客", notes = "移除分组下的游客")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.DELETE, operTitle = "移除分组下的游客", operDesc = "移除分组下的游客")
    @PostMapping("/removeGroupTourist")
    public Result removeGroupTourist(@RequestBody @Valid RemoveGroupTouristReq req) {
        return iSeriesOrderTouristInfoService.removeGroupTourist(req,getCurrentUser(getRequest()).getId());
    }


    @ApiOperation(value = "發票", notes = "预览（旅客信息-打印發票-预览）")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.QUERY, operTitle = "旅客信息-打印發票-预览", operDesc = "旅客信息-打印發票-预览")
    @PostMapping("/preview/invoice")
    public Result<CustomOrderTouristInfoPreviewInvoiceDTO> previewInvoice(@RequestBody @Valid SeriesOrderTouristInfoPreviewInvoiceReq req) {
        return iSeriesOrderTouristInfoService.previewInvoice(req, getCurrentUser(getRequest()));
    }

    @ApiOperation(value = "获取房间数范围", notes = "获取房间数范围")
    @OperationLogAnnotation(operModul = OperationLogModel.ORDER, operType = OperationLogType.QUERY, operTitle = "获取房间数范围", operDesc = "获取房间数范围")
    @PostMapping("/calculate")
    public Result<SingleRoomCalculateDTO> calculate(@RequestBody @Valid SingleRoomCalculateReq req) {
        return iSeriesOrderTouristInfoService.calculate(req);
    }

    @ApiOperation(value = "导入旅客名单", notes = "导入旅客名单（叶冠峰）")
    @OperationLogAnnotation(operModul = OperationLogModel.FINANCE, operType = OperationLogType.UPDATE, operTitle = "导入旅客名单", operDesc = "导入旅客名单")
    @PostMapping("/export-in")
    public Result exportIn(@RequestPart("file") MultipartFile file,@RequestParam("order_id") Long orderId) {
        if (file.isEmpty()){
            throw new BusinessException(SystemError.SYS_409,"file");
        }
        List<ExcelTemp> tempList = new ArrayList<>();
        Workbook wb0 = null;
        InputStream inputStream = null;
        try {
            //文件后缀名
            String fileExtension = getFileExtension(file.getOriginalFilename());
            inputStream = file.getInputStream();
            //根据指定的文件输入流导入Excel从而产生Workbook对象
            if ("xls".equals(fileExtension)){
                wb0 = new HSSFWorkbook(inputStream);
            }else if ("xlsx".equals(fileExtension)){
                wb0 = new XSSFWorkbook(inputStream);
            }
            if (wb0 != null){
                //获取Excel文档中的第一个表单
                Sheet sht0 = wb0.getSheetAt(0);
                //对Sheet中的每一行进行迭代
                for (Row r : sht0) {
                    //如果当前行的行号（从0开始）未达到2（第三行）则从新循环
                    if (r.getRowNum() < 2) {
                        continue;
                    }
                    //设置单元格类型
                    Cell cell1 = r.getCell(0);
                    cell1.setCellType(CellType.STRING);
                    Cell cell2 = r.getCell(1);
                    cell2.setCellType(CellType.STRING);
                    Cell cell3 = r.getCell(2);
                    cell3.setCellType(CellType.STRING);
                    Cell cell4 = r.getCell(3);
                    cell4.setCellType(CellType.STRING);
                    Cell cell5 = r.getCell(4);
                    cell5.setCellType(CellType.STRING);
                    Cell cell6 = r.getCell(5);
                    cell6.setCellType(CellType.STRING);
                    Cell cell7 = r.getCell(6);
                    cell7.setCellType(CellType.STRING);
                    Cell cell8 = r.getCell(7);
                    cell8.setCellType(CellType.STRING);
                    Cell cell9 = r.getCell(8);
                    cell9.setCellType(CellType.STRING);
                    Cell cell10 = r.getCell(9);
                    cell10.setCellType(CellType.STRING);
                    Cell cell11 = r.getCell(10);
                    cell11.setCellType(CellType.STRING);
                    Cell cell12 = r.getCell(11);
                    cell12.setCellType(CellType.STRING);
                    Cell cell13 = r.getCell(12);
                    cell13.setCellType(CellType.STRING);
                    Cell cell14 = r.getCell(13);
                    cell14.setCellType(CellType.STRING);
                    Cell cell15 = r.getCell(14);
                    cell15.setCellType(CellType.STRING);
                    Cell cell16 = r.getCell(15);
                    cell16.setCellType(CellType.STRING);
                    Cell cell17 = r.getCell(16);
                    cell17.setCellType(CellType.STRING);
                    Cell cell18 = r.getCell(17);
                    cell18.setCellType(CellType.STRING);
                    Cell cell19 = r.getCell(18);
                    cell19.setCellType(CellType.STRING);
                    Cell cell20 = r.getCell(19);
                    cell20.setCellType(CellType.STRING);
                    Cell cell21 = r.getCell(20);
                    cell21.setCellType(CellType.STRING);
                    Cell cell22 = r.getCell(21);
                    cell22.setCellType(CellType.STRING);
                    Cell cell23 = r.getCell(22);
                    cell23.setCellType(CellType.STRING);
                    Cell cell24 = r.getCell(23);
                    cell24.setCellType(CellType.STRING);
                    Cell cell25 = r.getCell(24);
                    cell25.setCellType(CellType.STRING);
                    Cell cell26 = r.getCell(25);
                    cell26.setCellType(CellType.STRING);
                    Cell cell27 = r.getCell(26);
                    cell27.setCellType(CellType.STRING);
                    Cell cell28 = r.getCell(27);
                    cell28.setCellType(CellType.STRING);
                    //创建实体类
                    ExcelTemp temp = new ExcelTemp();
                    //封装实体类属性
                    temp.setId(Long.valueOf(cell1.getStringCellValue()));
                    temp.setTouristTypeName(cell2.getStringCellValue());
                    temp.setCnSurname(cell3.getStringCellValue());
                    temp.setCnName(cell4.getStringCellValue());
                    temp.setEnSurname(cell5.getStringCellValue());
                    temp.setEnName(cell6.getStringCellValue());
                    Integer genger = getGenger(cell7.getStringCellValue());
                    temp.setGender(genger);
                    Long nationId = iSeriesOrderTouristInfoService.getNationId(cell11.getStringCellValue());
                    temp.setNationId(nationId);
                    temp.setNation(cell8.getStringCellValue());
                    temp.setMobileAreaCode(cell8.getStringCellValue());
                    temp.setMobile(cell9.getStringCellValue());
                    temp.setBirthday(DateUtil.parse(cell10.getStringCellValue(),"yyyyMMdd"));
                    temp.setEmail(cell12.getStringCellValue());
                    temp.setRemark(cell13.getStringCellValue());

                    Long certificateTypeId1 = iSeriesOrderTouristInfoService.getCertificateTypeId(cell14.getStringCellValue());
                    temp.setCertificateTypeId1(certificateTypeId1);
                    temp.setCertificateType1(cell14.getStringCellValue());
                    temp.setCertificateNumber1(cell15.getStringCellValue());
                    if (StringUtils.isNotBlank(cell16.getStringCellValue())){
                        temp.setCertificateValidDate1(DateUtil.parse(cell16.getStringCellValue(),"yyyyMMdd"));
                    }
                    temp.setCertificatePlace1(cell17.getStringCellValue());

                    Long certificateTypeId2 = iSeriesOrderTouristInfoService.getCertificateTypeId(cell18.getStringCellValue());
                    temp.setCertificateTypeId2(certificateTypeId2);
                    temp.setCertificateType2(cell18.getStringCellValue());
                    temp.setCertificateNumber2(cell19.getStringCellValue());
                    if (StringUtils.isNotBlank(cell20.getStringCellValue())){
                        temp.setCertificateValidDate2(DateUtil.parse(cell20.getStringCellValue(),"yyyyMMdd"));
                    }
                    temp.setCertificatePlace2(cell21.getStringCellValue());

                    Long certificateTypeId3 = iSeriesOrderTouristInfoService.getCertificateTypeId(cell22.getStringCellValue());
                    temp.setCertificateTypeId3(certificateTypeId3);
                    temp.setCertificateType3(cell22.getStringCellValue());
                    temp.setCertificateNumber2(cell23.getStringCellValue());
                    if (StringUtils.isNotBlank(cell24.getStringCellValue())){
                        temp.setCertificateValidDate3(DateUtil.parse(cell24.getStringCellValue(),"yyyyMMdd"));
                    }
                    temp.setCertificatePlace3(cell25.getStringCellValue());

                    temp.setEmergencyContactName(cell26.getStringCellValue());
                    temp.setEmergencyMobileAreaCode(cell27.getStringCellValue());
                    temp.setEmergencyMobile(cell28.getStringCellValue());
                    tempList.add(temp);
                }
            }
            System.out.println("旅客列表数据 =====>>> " + JSON.toJSONString(tempList));
            return iSeriesOrderTouristInfoService.exportIn(tempList,getCurrentUser(getRequest()).getId(),orderId);
        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessException(SystemError.SYS_437);
        }finally {
            try {
                inputStream.close();
            }catch (Exception e){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
    }

    @ApiOperation(value = "導出旅客模板", notes = "導出旅客模板（叶冠峰）")
    @OperationLogAnnotation(operModul = OperationLogModel.FINANCE, operType = OperationLogType.QUERY, operTitle = "導出旅客模板", operDesc = "導出旅客模板")
    @PostMapping("/export-out")
    public void exportOut(@RequestBody @Valid CustomOrderIdReq req) {
        ExcelData data = iSeriesOrderTouristInfoService.exportOut(req);
        if (data == null){
            throw new BusinessException(SystemError.FINANCE_BILL_17023);
        }
        try {
            ExportExcelUtils.exportExcel(getResponse(),"旅客名单模板.xlsx",data);
        }catch (Exception e){
            throw new BusinessException(SystemError.SYS_437);
        }
    }

    /**
     * 获取称谓
     * @param str
     * @return
     */
    private Integer getGenger(String str) {
        if ("先生".equals(str)){
            return 1;
        }else if ("女士".equals(str)){
            return 2;
        }else if ("小姐".equals(str)){
            return 3;
        }else if ("男童".equals(str)){
            return 4;
        }else if ("女童".equals(str)){
            return 5;
        }
        return null;
    }

}









